/**
 * @file response
 * @author shenli
 */

var http = require('http');
var statusCodes = http.STATUS_CODES;
var send = require('send');
var util = require('util');
var send = require('send');
var path = require('path');
var extname = path.extname;
var mime = send.mime;
var setCharset = require('./utils').setCharset;


var charsetReg = /;\s*charset\s*=/;

function Response() {
    this.statusCode = '';
}

util.inherits(Response, http.ServerResponse);

/**
 * send body
 *
 * @param  {string|number|object|Buffer} body
 * @return {}
 * @example
 * 	res.send(500);
 * 	res.send('Hello');
 * 	res.send('<p>am</p>');
 */
Response.prototype.send = function(body) {
    var chunk = body;
    var encoding;
    var type;

    if (typeof chunk === 'number' && arguments.length === 1) {
        if (!this.get('Content-Type')) {
            this.type('txt');
        }

        this.status(chunk);
        chunk = statusCodes[chunk];
    }

    switch (typeof chunk) {
        case 'string':
            if (!this.get('Content-Type')) {
                this.type('html');
            }
            break;
        case 'boolean':
        case 'number':
        case 'object':
            if (chunk === null) {
                chunk = ''
            } else {
                this.json(chunk);
            }

            break;
    }

    if (typeof chunk === 'string') {
        encoding = 'utf8';
        type = this.get('Content-Type');
        if (typeof type === 'string') {
            this.set('Content-Type', setCharset(type, 'utf-8'));
        }
    }

    if (this.fresh) {
        this.statusCode = 304;
    }

    this.end(chunk, encoding);

};

Response.prototype.status = function(status) {
    this.statusCode = status;
    return this;
};

Response.prototype.type = function(type) {
        var ct = type.indexOf('/') === -1 ? mime.lookup(type) : type;

        return this.set('Content-Type', ct);
    };

Response.prototype.get =  function(field) {
        return this.getHeader(field);
    };

Response.prototype.set = Response.prototype.header = function(field, val) {
    if (arguments.length === 2) {
        var value = Array.isArray(val) ? val.map(String) : String(val);

        if (field.toLowerCase() === 'content-type' && !charsetReg.test(value)) {
            var charset = mime.charsets.lookup(value.split(';')[0]);
            if (charset) {
                value += '; charset=' + charset.toLowerCase();
            }
        }

        this.setHeader(field, value);
    } else {
        for (var key in field) {
            this.set(key, field[key]);
        }
    }

    return this;
};

module.exports = new Response();
